package org.csu.xzypetstore.controller;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import org.csu.xzypetstore.domain.Account;
import org.csu.xzypetstore.domain.CodeUtil;
import org.csu.xzypetstore.domain.SmsUtil;
import org.csu.xzypetstore.service.AccountService;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

//@RestController
@Controller

@RequestMapping("/aa")
@SessionAttributes("account")
public class SmsController {

    @Autowired
    private AccountService accountService;

    @PostMapping(value = "/smsXxs")
    @ResponseBody
    public String smsXxs(HttpServletRequest req, String phone) throws Exception {

        HttpSession session = req.getSession();

        Map<String,Object> map = new HashMap<String,Object>(16);
        // 验证码（指定长度的随机数）
        String code = CodeUtil.generateVerifyCode(6);
        System.out.println(phone+"  "+code);
        String templateParam = "{\"code\":\""+code+"\"}";
        SendSmsResponse response = SmsUtil.sendSms(phone, templateParam);
        map.put("verifyCode",code);
        map.put("phone",phone);
        session.setAttribute("PhoneCode", code);
        if( response.getCode().equals("OK")) {
            map.put("status","success");
            return "1";
        } else {
            map.put("isOk","false");
            return "0";
        }
    }

    @GetMapping("/PhoneSign")
    public String  login(){

        return "account/PhoneNumberOn";
    }

    @PostMapping("/yan")
    public String PhoneYan(HttpServletRequest req, Model model)
    {
        HttpSession session = req.getSession();
        String PhoneCode = req.getParameter("code");
        String sessionCode = (String) req.getSession().getAttribute("PhoneCode");

        if(PhoneCode.equals(sessionCode))
        {
            Account account = accountService.getAccount("ACID","ACID");
            model.addAttribute("account",account);
            return "catalog/main";
        }
        else {
            return "account/PhoneNumberOn";
        }
    }

}

